﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using KLS.PPDS.Utility;
using KLS.PPDS.Utilities.Entity;
using log4net;
using KLS.PPDS.Resources;

namespace KLS.PPDS.Utilities
{
    /// <summary>
    /// 
    /// </summary>
    public class FileUtil
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(FileUtil));

        public static string RePlaceSpecialCharecter(string name) 
        {
            name = name.Replace(@"\", "-").Replace(@"/", "-").Replace(@":", "-").Replace(@":", "-").Replace(@"*", "-").Replace("\"", "-").Replace("?", "-").Replace("<", "-").Replace(">", "-").Replace("|", "-");
            return name;
        }

        public static byte[] GetFile(string s)
        {

            var fs = System.IO.File.OpenRead(s);
            var data = new byte[fs.Length];
            var br = fs.Read(data, 0, data.Length);
            if (br != fs.Length)
                throw new System.IO.IOException(s);

            fs.Flush();
            fs.Close();
            return data;
        }

      
        public static void CreateDirectory(string directory) 
        {
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
        }

        public static string WriteTextFile(string txt, string directory, string fileName, bool append) 
        {
            var result = string.Empty;

            var file = Path.Combine(directory, fileName);

            if (!Directory.Exists(directory)) 
            {
                Directory.CreateDirectory(directory);
            }

            try
            {
                if (!File.Exists(file)) 
                {
                    FileStream fs = File.Create(file);
                    fs.Close();
                }

                if ((File.GetAttributes(file) & FileAttributes.ReadOnly) != FileAttributes.ReadOnly)
                {
                    var strmWriter = new StreamWriter(file, append);
                    strmWriter.WriteLine(txt);
                    strmWriter.Close();
                    strmWriter.Dispose();

                }
                else 
                {
                    result = CommonMessage.CommentFileReadonly;
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
            
            return result;
        }

        /// <summary>
        /// Required, but not used
        /// </summary>
        /// <returns>true</returns>
        public static bool ThumbnailCallback()
        {
            return true;
        }

        public static string SaveThumbnails(Stream srtm, string dir, string fileName)
        {
            if (!Directory.Exists(dir)) 
            {
                Directory.CreateDirectory(dir);
            }

            try
            {
                var image = System.Drawing.Image.FromStream(srtm);

                var thumbnailImage = image.GetThumbnailImage(WebConfig.ThumbnailsWidth, WebConfig.ThumbnailsHeight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

                thumbnailImage.Save(Path.Combine(dir, fileName));
            }
            catch (Exception ex)
            {
                log.Error(ex);
               // log4net.
            }

            return string.Empty;
        }



        /// <summary>
        /// Function to get byte array from a file
        /// </summary>
        /// <param name="_FileName">File name to get byte array</param>
        /// <returns>Byte Array</returns>
        //public static byte[] FileToByteArray(string _FileName)
        //{
        //    byte[] _Buffer = null;

        //    try
        //    {
        //        // Open file for reading
        //        var _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);

        //        // attach filestream to binary reader
        //        var _BinaryReader = new System.IO.BinaryReader(_FileStream);

        //        // get total byte length of the file
        //        var _TotalBytes = new System.IO.FileInfo(_FileName).Length;

        //        // read entire file into buffer
        //        _Buffer = _BinaryReader.ReadBytes((Int32)_TotalBytes);

        //        // close file reader
        //        _FileStream.Close();
        //        _FileStream.Dispose();
        //        _BinaryReader.Close();
        //    }
        //    catch (Exception _Exception)
        //    {
        //        // Error
        //       // Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
        //    }

        //    return _Buffer;
        //}

        public static void DeleteImageFile(string fullPathFileName) 
        {
            if (File.Exists(fullPathFileName)) 
            {
                File.Delete(fullPathFileName);
            }
        }

        public static void DeleteFolder(string basePath) 
        {
            if (Directory.Exists(basePath)) 
            {
                Directory.Delete(basePath, true);
            }
            
        }

        public static bool MoveFolder(string oldCustomerFolderName, string newCustomerFolderName)
        {

            if (Directory.Exists(newCustomerFolderName).Equals(false)) 
            {
                Directory.CreateDirectory(newCustomerFolderName);
            }

            if (Directory.Exists(oldCustomerFolderName).Equals(true))
            {
                var DI = new DirectoryInfo(oldCustomerFolderName).GetDirectories("*.*", SearchOption.TopDirectoryOnly);
                foreach (var di in DI)
                {
                    di.MoveTo(Path.Combine(newCustomerFolderName, di.Name));
                }

               // var FI = Directory.GetFiles(oldCustomerFolderName);

                //var di = new DirectoryInfo(oldCustomerFolderName);
                //var FI = di.GetFiles();

                foreach (var fi in new DirectoryInfo(oldCustomerFolderName).GetFiles())
                {

                    //fi.MoveTo(Path.Combine(newCustomerFolderName, di.Name));
                    //File.Move(Path.Combine(oldCustomerFolderName, fi), Path.Combine(newCustomerFolderName, fi));
                    fi.MoveTo(Path.Combine(newCustomerFolderName, fi.Name));
                }
            }

            return false;
        }

        public static bool RemaneDirectory(string oldDirectory, string newDirectory)
        {
            if(Directory.Exists(oldDirectory))
            {
                Directory.Move(oldDirectory, newDirectory);
            }
            return false;
        }

        public static bool RenameFile(string basePath, string oldFileName, string newFileName) 
        {

            oldFileName = Path.Combine(basePath, oldFileName);

            newFileName = Path.Combine(basePath, newFileName);

            if (!File.Exists(newFileName) && !oldFileName.Equals(newFileName))             
            {
                File.Move(oldFileName, newFileName);
            }

            return false;
        }

        //to show uploaded file name
        public static string TextGetOriginalFileName(string fileName) 
        {
            //var result = fileName.Substring(fileName.IndexOf(CommonConstant.PrefixAttatchTextFile) + 2);
            var result = fileName;
            return result;
        }

        //get thumbsnail file name
        public static string ImageGetThumbnailsFileName(string fileName)
        {
            //var strat = fileName.IndexOf(CommonConstant.PrefixStartCountFile) + 2;
            //var length = fileName.IndexOf(CommonConstant.PrefixEndCount) - strat;
            //var result = fileName.Substring(strat, length) +"_"+ ImageGetOriginalFileName(fileName);

            return  fileName;
            //return result;
        }

        public static int GetImgaeFileNumber(string fileName) 
        {
            var strat = fileName.IndexOf(CommonConstant.PrefixStartCountFile) + 2;
            var length = fileName.IndexOf(CommonConstant.PrefixEndCount) - strat;
            var result = fileName.Substring(strat, length) ;

            return Convert.ToInt32(result);
        }

        //When clear file name form both cutout & retouch
        public static string GetClearFileName(string fileName) 
        {
            var strat = fileName.IndexOf(CommonConstant.PrefixStartCountFile) + 2;
            var length = fileName.IndexOf(CommonConstant.PrefixEndCount) - strat;
            var count = fileName.Substring(strat, length);

            var oFileName = ImageGetOriginalFileName(fileName);

            return GetDiskImageFileName(count, oFileName);
        }

        //generate image file name
        public static string GetDiskImageFileName(string count, string fileName) 
        {
            //return CommonConstant.PrefixStartCountFile + count + CommonConstant.PrefixEndCount + CommonConstant.PrefixAttatchImageFile + fileName;
            return  count +  fileName;
        }

        //Get the basic disk file name (when prefixed by retouched/cutout)
        public static string GetDiskImageOnlyFileName(string fileName)
        {
            return fileName.Substring(fileName.IndexOf(CommonConstant.PrefixStartCountFile));
        }

        //Generate text file name
        public static string GetDiskTextFileName(string count, string fileName)
        {
            //return CommonConstant.PrefixStartCountFile + count + CommonConstant.PrefixEndCount + CommonConstant.PrefixAttatchTextFile + fileName;
            return fileName;
        }

        //To show the uploaded file name
        public static string ImageGetOriginalFileName(string fileName)
        {
            var result = fileName.Substring(fileName.IndexOf(CommonConstant.PrefixAttatchImageFile) + 2);

            return result;
        }


        public static string ImageGetOriginalFilePrefixName(string fileName)
        {
            var result = fileName.Substring(0, fileName.IndexOf(CommonConstant.PrefixAttatchImageFile) + 1);

            return result;
        }

        public static List<ArticleFile> NewGetImageFiles(string path) 
        {
            var fileNames = GetFullPathFilesInsideFolder(path, GetImageFileExtension());

            var articleFile = new ArticleFile();
            var f = new FileInfo(path);

            var list = new List<ArticleFile>();
            foreach (var file in fileNames) 
            {
                f = new FileInfo(file);
                articleFile = new ArticleFile();

                articleFile.FileName = f.Name;
                articleFile.FileOriginalName = ImageGetOriginalFileName(f.Name);
                articleFile.Info = f;
                articleFile.FileSize = (f.Length/1024)/1024;
               // articleFile.Number = GetImgaeFileNumber(f.Name);
               //articleFile.Image = FileToByteArray(f.FullName);
                list.Add(articleFile);
            }

            list = list.OrderBy(c => c.Number).ToList();
            return list;
        }


        public static List<ArticleFile> NewGetTextFiles(string path)
        {
            var fileNames = GetFullPathFilesInsideFolder(path);

            var articleFile = new ArticleFile();
            var f = new FileInfo(path);

            var list = new List<ArticleFile>();
            foreach (var file in fileNames)
            {
                f = new FileInfo(file);
                articleFile = new ArticleFile();

                articleFile.FileName = f.Name;
                articleFile.FileOriginalName = TextGetOriginalFileName(f.Name);
                articleFile.Info = f;
                articleFile.FileSize = (f.Length / 1024) / 1024;
                list.Add(articleFile);
            }
            list = list.OrderBy(c => c.FileOriginalName).ToList();
            return list;
        }

        public static List<string> GetImageFiles(string path) 
        {            

            return GetFilesInsideFolder(path, GetImageFileExtension());
        }


        public static List<string> GetTextFiles(string path)
        {
            return GetFilesInsideFolder(path, GetTextFileExtension());
        }


        public static List<string> GetFullPathFilesInsideFolder(string path, List<string> extnt)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var files = new List<string>();

            var onlyFilesName = new List<string>();

            foreach (var ext in extnt)
            {
                files.AddRange((Directory.GetFiles(path, ext)));
            }


            return files;
        }

        public static List<string> GetFullPathFilesInsideFolder(string path)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var files = new List<string>();

            var onlyFilesName = new List<string>();

            //foreach (var ext in extnt)
            {
                files.AddRange((Directory.GetFiles(path)));
            }


            return files;
        }


        public static List<string> GetFilesInsideFolder(string path, List<string> extnt)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var files = new List<string>();

            var onlyFilesName = new List<string>();

            foreach (var ext in extnt) 
            {
                files.AddRange(( Directory.GetFiles(path,ext)));                
            }

            foreach (var file in files) 
            {
                onlyFilesName.Add(Path.GetFileName(file));
            }

            return onlyFilesName;
        }

        private static List<string> GetTextFileExtension()
        {
            var array = WebConfig.TextFileExtensions.Split('|');
            return array.ToList();
        }

        private static List<string> GetImageFileExtension()
        {
            var array = WebConfig.ImageFileExtensions.Split('|');
            return array.ToList();
        }
    }
}
